package com.cxyd.modules.wms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cxyd.common.page.PageData;
import com.cxyd.common.exception.RootException;
import com.cxyd.common.service.impl.CrudServiceImpl;
import com.cxyd.common.utils.ConvertUtils;
import com.cxyd.common.utils.ProcResult;
import com.cxyd.modules.core.service.SerialNumberService;
import com.cxyd.modules.sys.dto.SysUserDTO;
import com.cxyd.modules.sys.service.SysUserService;
import com.cxyd.modules.wms.dao.PurchaseDao;
import com.cxyd.modules.wms.dto.PurchaseDTO;
import com.cxyd.modules.wms.entity.PurchaseEntity;
import com.cxyd.modules.wms.service.PurchaseService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;
import java.util.Map;

/**
 * 入库主单
 *
 * @author g_Cycle gengruyi01@163.com
 * @since 1.0.0 2023-04-27
 */
@Service
public class PurchaseServiceImpl extends CrudServiceImpl<PurchaseDao, PurchaseEntity, PurchaseDTO> implements PurchaseService {
    private final SysUserService userService;
    private final SerialNumberService serialNumberService;

    public PurchaseServiceImpl(SysUserService userService, SerialNumberService serialNumberService) {
        this.userService = userService;
        this.serialNumberService = serialNumberService;
    }

    @Override
    public PageData<PurchaseDTO> page(Map<String, Object> params) {
        //1.查询主单信息
        final IPage<PurchaseEntity> page = baseDao.selectPage(
                getPage(params, "", false),
                getWrapper(params)
        );
        //2.获取用户信息
        final List<SysUserDTO> userList = userService.getList();
        //3.将creator与updater的username通过id进行绑定
        page.getRecords().forEach(entity -> {
            if (entity.getCreator() != null) {
                entity.setCreatorName(userService.getUsernameById(entity.getCreator(), userList));
            }
            if (entity.getUpdater() != null) {
                entity.setUpdaterName(userService.getUsernameById(entity.getUpdater(), userList));
            }
        });
        return getPageData(page, PurchaseDTO.class);
    }

    @Override
    public QueryWrapper<PurchaseEntity> getWrapper(Map<String, Object> params) {
        String id = (String) params.get("id");
        String purchaseNo = (String) params.get("purchaseNo");
        String deliverNo = (String) params.get("deliverNo");
        String purchaseSt = (String) params.get("purchaseSt");

        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        wrapper.eq(StringUtils.isNotBlank(purchaseNo), "PURCHASE_NO", purchaseNo);
        wrapper.eq(StringUtils.isNotBlank(purchaseSt), "PURCHASE_ST", purchaseSt);
        wrapper.like(StringUtils.isNotBlank(deliverNo), "deliver_no", deliverNo);
        //新增排序
        wrapper.orderBy(true, true, "(CASE purchase_st " +
                "WHEN 1 THEN 0 " +
                "WHEN 0 THEN 1 " +
                "WHEN 2 THEN 2 " +
                "WHEN 9 THEN 3 " +
                "ELSE 4 END)");
        wrapper.orderBy(true, true, "create_date");
        return wrapper;
    }

    @Override
    public void save(PurchaseDTO dto) {
        //1.获取订单编号
        String purchaseNo = serialNumberService.getSerialNumberByCode("purchase");
        //2.将dto转换为单据实体类
        final PurchaseEntity entity = ConvertUtils.sourceToTarget(dto, PurchaseEntity.class);
        //3.单据编号填充至实体类
        entity.setPurchaseNo(purchaseNo);
        //4.将数据写入数据库
        insert(entity);
    }

    @Override
    public PurchaseDTO selectByParams(Map<String, Object> params) {
        String purchaseNo = (String) params.get("purchaseNo");
        String deliverNo = (String) params.get("deliverNo");
        String spuName = (String) params.get("spuName");
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(purchaseNo), "purchase_no", purchaseNo);
        wrapper.eq(StringUtils.isNotBlank(deliverNo), "deliver_no", deliverNo);
        wrapper.like(StringUtils.isNotBlank(spuName), "spu_name", spuName);
        final PurchaseEntity entity = baseDao.selectOne(wrapper);
        return ConvertUtils.sourceToTarget(entity, PurchaseDTO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(@RequestBody Long[] ids) {
        for (int i = 0; i < ids.length; i++) {
            deletePurchaseById(ids[i]);
        }
    }

    private void deletePurchaseById(Long id) {
        PurchaseEntity entity = baseDao.selectById(id);
        //判断明细状态是否为初始状态
        if (entity.getPurchaseSt() != 0) {
            throw new RootException("只有[初始]状态主单才可以删除");
        }
        //删除
        baseDao.deleteById(id);
    }

    @Override
    public ProcResult purchaseRegister(Map<String, Object> params) {
        //对主要参数进行校验(contNo,detailId,actlQty等)
        final String contNo = (String) params.get("contNo");
        if (StringUtils.isBlank(contNo)) {
            return new ProcResult().result("123", "托盘条码不能为空!");
        }
        final String detailId = (String) params.get("detailId");
        if (StringUtils.isBlank(detailId)) {
            return new ProcResult().result("123", "明细ID不能为空!");
        }
        final String actlQty = (String) params.get("actlQty");
        if (StringUtils.isBlank(actlQty)) {
            return new ProcResult().result("123", "件数不能为空!");
        }
        final String spuSize = (String) params.get("spuSize");
        if (StringUtils.isBlank(spuSize)) {
            return new ProcResult().result("123", "尺寸不能为空!");
        }
        final String spuWeight = (String) params.get("spuWeight");
        if (StringUtils.isBlank(spuWeight)) {
            return new ProcResult().result("123", "磅重不能为空!");
        }
        String userId = (String) params.get("userId");
        if (StringUtils.isBlank(userId)) {
            params.put("userId", 1004L);
        }
        baseDao.procPurchaseRegister(params);
        final String code = (String) params.get("code");
        final String msg = (String) params.get("msg");
        return new ProcResult().result(code, msg);
    }

    @Override
    public ProcResult residualBackRegister(Map<String, Object> params) {
        //对主要参数进行校验(contNo,detailId,actlQty等)
        final String contNo = (String) params.get("contNo");
        if (StringUtils.isBlank(contNo)) {
            return new ProcResult().result("123", "托盘条码不能为空!");
        }
        String stnNo = (String) params.get("stationNo");
        if (StringUtils.isBlank(stnNo)) {
            return new ProcResult().result("123", "所选站台不能为空!");
        }
        final String spuNo = (String) params.get("spuNo");
        if (StringUtils.isBlank(spuNo)) {
            return new ProcResult().result("123", "物料编号不能为空!");
        }
        final String spuSize = (String) params.get("spuSize");
        if (StringUtils.isBlank(spuSize)) {
            return new ProcResult().result("123", "尺寸不能为空!");
        }
        final String actlQty = (String) params.get("actlQty");
        if (StringUtils.isBlank(actlQty)) {
            return new ProcResult().result("123", "件数不能为空!");
        }
        String userId = (String) params.get("userId");
        if (StringUtils.isBlank(userId)) {
            params.put("userId", 1004L);
        }
        baseDao.procBackRegister(params);
        final String code = (String) params.get("code");
        final String msg = (String) params.get("msg");
        return new ProcResult().result(code, msg);
    }

    @Override
    public ProcResult importExcel(Map<String, Object> params) {

        final String code = (String) params.get("code");
        final String msg = (String) params.get("msg");
        return new ProcResult().result(code, msg);
    }
}